package BookManagement.controller;

import BookManagement.domain.*;
import BookManagement.service.BookService;
import BookManagement.service.BorrowService;
import BookManagement.service.CommentService;
import BookManagement.service.UserService;
import org.apache.commons.fileupload.FileItem;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    @Qualifier("borrowService")
    private BorrowService borrowService;

    @Autowired
    @Qualifier("bookService")
    private BookService bookService;

    @Autowired
    @Qualifier("commentService")
    private CommentService commentService;

    //ISBN查书，唯一查找
    @RequestMapping("/findBookByISBN")
    public ModelAndView findBookByISBN(String bookISBN){
        ModelAndView mav=new ModelAndView();
        Book book=bookService.findByISBN(bookISBN);
        new CommentController().listButton(mav,bookISBN,commentService);
        mav.addObject("book",book);
        mav.setViewName("guest/guestDetails");
        return mav;
    }

    //用户或游客查第几页的全部书
    @RequestMapping("/findAllBooks")
    public ModelAndView findAllBooks(String pageNo){
        ModelAndView mav=new ModelAndView();
        Page p = new Page(pageNo,8,bookService.getTotalBooks());
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("start",p.getStart());
        map.put("size", p.getPageSize());
        List<Book> bookList = bookService.findAllBooks(map);
        mav.addObject("bookList", bookList);
        mav.addObject("page", p);
        mav.setViewName("guest/guestList");
        return mav;
    }

    //管理员查看全部书
    @RequestMapping("/findAllBooksAdmin")
    public ModelAndView findAllBooksAdmin(String pageNo){
        ModelAndView mav=new ModelAndView();
        Page p = new Page(pageNo,10,bookService.getTotalBooks());
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("start",p.getStart());
        map.put("size", p.getPageSize());
        List<Book> bookList = bookService.findAllBooks(map);
        mav.addObject("bookList", bookList);
        mav.addObject("page", p);
        mav.setViewName("admin/books/allBook");
        return mav;
    }

    //书名查书，模糊搜索，需分页
    @RequestMapping("/findBookByBookNameOrAuthor")
    public ModelAndView findBookByBookName(String str,String pageNo){
        int total=bookService.getTotalBooks();
        Page p=new Page(pageNo,10,total);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",str);
        map.put("start",p.getStart());
        map.put("size",p.getPageSize());
        List<Book> bookList=bookService.findByBookNameOrAuthor(map);
        ModelAndView mav=new ModelAndView();
        mav.addObject("bookList",bookList);
        mav.addObject("str",str);
        mav.addObject("page",p);
        mav.setViewName("guest/guestSearch");
        return mav;
    }

    //书名查书，模糊搜索，需分页，管理员
    @RequestMapping("/findBookByBookNameOrAuthorAdmin")
    public ModelAndView findBookByBookNameAdmin(String str,String pageNo){
        int total=bookService.getTotalBooksBy(str);
        Page p=new Page(pageNo,10,total);
        HashMap<String,Object> map=new HashMap<>();
        map.put("str",str);
        map.put("start",p.getStart());
        map.put("size",p.getPageSize());
        List<Book> bookList=bookService.findByBookNameOrAuthor(map);
        ModelAndView mav=new ModelAndView();
        mav.addObject("bookList",bookList);
        mav.addObject("str",str);
        mav.addObject("page",p);
        mav.setViewName("admin/books/searchBook");
        return mav;
    }

    //跳转添加书界面
    @RequestMapping("/toAddBook")
    public ModelAndView toAddBook(){
        ModelAndView mav=new ModelAndView("admin/books/addBook");
        return mav;
    }

    //添加书
    @RequestMapping("/addBook")
    public void addBook(String bookISBN, String bookName, Integer bookCounts, String bookPrices, String detail, String author,@RequestParam("photo") CommonsMultipartFile file, HttpSession hs){
        ModelAndView mav=new ModelAndView();
        if(bookISBN==null||bookName==null){
            mav=new ModelAndView("findSucc","msg","书本ISBN或书名为空");
//            return mav;
        }
        if(bookService.findByISBN(bookISBN)!=null){
            mav=new ModelAndView("findSucc","msg","书籍已存在");
//            return mav;
        }
        String photoAddr=new String();
        if(!file.isEmpty()){
            String path=hs.getServletContext().getRealPath("/bookImages/");
            String fileName=file.getOriginalFilename();
            String filetype=fileName.substring(fileName.lastIndexOf("."));
            File target=new File(path,bookISBN+filetype);
            photoAddr="/bookImages/"+bookISBN+filetype;
            try{
                file.getFileItem().write(target);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        Book b=new Book(bookISBN,bookName,bookCounts,Double.parseDouble(bookPrices),detail,author,photoAddr);
        bookService.addBook(b);
        mav=new ModelAndView("findSucc","msg","添加成功");
//        return mav;
    }

    //读取照片
    @RequestMapping("/readPhoto")
    public void readPhoto(String bookISBN, HttpServletResponse response,HttpSession hs){
        try{
            Book b = bookService.findByISBN(bookISBN);
            FileInputStream fis=new FileInputStream(hs.getServletContext().getRealPath(b.getPhoto()));
            byte[] d=new byte[fis.available()];
            fis.read(d);
            fis.close();
            response.setContentType("img/*");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(d);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //根据ISBN删除书
    @RequestMapping("/deleteBookByISBN/{bookISBN}/{pageNo}")
    public ModelAndView deleteBookByISBN(@PathVariable("bookISBN") String ISBN,@PathVariable("pageNo")String pageNo, HttpSession hs) throws IOException {
        ModelAndView mav=new ModelAndView();
        Book b=bookService.findByISBN(ISBN);
        if(b==null){
            mav.setViewName("findSucc");
            mav.addObject("delSucc","该ISBN码对应的书籍不存在");
            return mav;
        }
        String photoPath=hs.getServletContext().getRealPath(b.getPhoto());
        Path path = Paths.get(photoPath);
        Files.delete(path);
        int i=bookService.deleteBookByISBN(ISBN);
        mav=new ModelAndView("redirect:/book/findAllBooksAdmin?pageNo="+pageNo,"delSucc","删除成功");
        return mav;
    }

    //跳转更新书界面
    @RequestMapping("/toUpdateBook")
    public ModelAndView toUpdateBook(String bookISBN,HttpSession hs){
        Book book=bookService.findByISBN(bookISBN);
        hs.setAttribute("photoID",bookISBN);
        ModelAndView mav=new ModelAndView("admin/books/updateBook");
        mav.addObject("book",book );
        return mav;
    }

    //更新书，一般情况下更新数目、价格、详情、图片
    @RequestMapping("/updateBook")
    public ModelAndView updateBook(String bookISBN, String bookName, Integer bookCounts, String bookPrices, String detail, String author,@RequestParam("photo") CommonsMultipartFile file, HttpSession hs) throws IOException {
        ModelAndView mav=new ModelAndView();
        Book b=bookService.findByISBN(bookISBN);
        File f=new File(hs.getServletContext().getRealPath(b.getPhoto()));
        if(!file.isEmpty()&&f.exists()){
            Files.delete(Paths.get(hs.getServletContext().getRealPath(b.getPhoto())));
        }
        String photo=null;
        if(!file.isEmpty()){
            String path=hs.getServletContext().getRealPath("/bookImages/");
            String fileName=file.getOriginalFilename();
            String filetype=fileName.substring(fileName.lastIndexOf("."));
            File target=new File(path,bookISBN+filetype);
            photo="/bookImages/"+bookISBN+filetype;
            try{
                file.getFileItem().write(target);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        b.setBookName(bookName);b.setBookCounts(bookCounts);b.setBookPrices(Double.parseDouble(bookPrices));b.setDetail(detail);b.setAuthor(author);
        if(photo!=null)b.setPhoto(photo);
        int i=bookService.updateBook(b);
        if(i>0){
            mav.setViewName("/admin/books/updateBookSuccessfully");
            return mav;
        }else{
            mav.setViewName("/admin/books/updateBookFail");
            return mav;
        }
    }

    //查看书本借书
    @RequestMapping("/showBorrowByBook")
    public ModelAndView showBorrowByBook(HttpSession hs,String pageNo,String bookISBN){
        ModelAndView mav=new ModelAndView();
        User user =userService.findUserByUsername( (String) hs.getAttribute("usercurrent"));
        if(user==null){
            return new ModelAndView("redirect:/account/toLogin");
        }
        Page p=new Page(pageNo,10,borrowService.findBorrowCountByBook(bookISBN));
        HashMap<String,Object>map=new HashMap<>();
        map.put("start",p.getStart());
        map.put("size",p.getPageSize());
        map.put("bookISBN",bookISBN);
        List<Borrow> borrowList = borrowService.searchAllBorrowingBookWithBookISBN(map);
        Book b=bookService.findByISBN(bookISBN);
        mav.addObject("borrowList",borrowList);
        mav.addObject("bookName",b.getBookName());
        mav.addObject("page",p);
//        mav.setViewName("/user/allBorrowOfUser");
        return mav;
    }


 }
